import React, { Component, useState } from 'react';
import { Provider } from 'react-redux';
import { getAppInfo, getSystemInfoSync } from '@ray-js/ray';
import res from '@/res/images';
import { devices, dpKit } from './devices';
import { updateThemeType } from './redux/modules/themeSlice';
import { initializeSystemInfo } from './redux/modules/systemInfoSlice';
import store from './redux';
import './styles/index.less';
// eslint-disable-next-line import/order
import ConfigProvider from '@ray-js/components-ty-config-provider';
import { initializeAppInfo } from './redux/modules/appInfoSlice';
import {
  CLOUD_DATA_KEYS_MAP,
  DEFAULT_GROUP_KEY_MAP,
  DEFAULT_GROUP_NAME_MAP,
  DEFAULT_SWITCH_NAME_MAP,
} from './constant';
import { initCloud } from './redux/modules/cloudStateSlice';
import { getCloudData } from './api';

console.log('🚀 ~ devices:', devices);

interface Props {
  devInfo: DevInfo;
  // eslint-disable-next-line react/require-default-props
  extraInfo?: Record<string, any>;
}

interface State {
  devInfo: DevInfo;
}

function Panel(config: any) {
  const [primaryColor, setPrimaryColor] = useState('#3678e3');
  const [tabBarStyle, setTabBarStyle] = useState({
    textColor: 'var(--app-B5-N2)',
    selectedColor: 'var(--app-M4)',
    backgroundColor: 'var(--app-B5)',
  });

  return (
    <ConfigProvider config={{ primaryColor, tabBar: tabBarStyle }}>
      {config.children}
    </ConfigProvider>
  );
}

const composeLayout = (SubComp: React.ComponentType<any>) => {
  const { dispatch } = store;
  return class PanelComponent extends Component<Props, State> {
    async onLaunch(object: any) {
      console.log('=== App onLaunch', object);
      devices.common.onInitialized(device => {
        dpKit.init(device);
      });
      devices.common.init();
      const systemInfo = getSystemInfoSync();
      const { theme } = systemInfo;
      getAppInfo({
        success: data => {
          dispatch(initializeAppInfo(data));
        },
        fail: err => {
          console.log('=== getAppInfoError', err);
        },
      });

      dispatch(initializeSystemInfo(systemInfo));
      dispatch(updateThemeType(theme));
      devices.lamp.init();
      devices.lamp.onInitialized(device => {
        this.initCloudData();
      });
    }

    async initCloudData() {
      ty.showLoading({ title: '' });

      // @ts-ignore
      return devices.lamp.model.abilities.storage
        .getAll()
        .then(data => {
          console.log("🚀 ~ initCloudData ~ data:", JSON.stringify(data))
          const switchName = {};
          const switchPic = {};

          const groupNames = {};

          Object.values(CLOUD_DATA_KEYS_MAP).forEach((k, i) => {
            switchName[k] = data[k]?.data?.value?.name || DEFAULT_SWITCH_NAME_MAP[k];
            switchPic[k] = data[k]?.data?.value?.pic || res.defaultAreaPic;
          });

          Object.values(DEFAULT_GROUP_KEY_MAP).forEach((k, i) => {
            groupNames[k] = data[k]?.data?.value || DEFAULT_GROUP_NAME_MAP[k];
          });

          store.dispatch(
            initCloud({
              switchName,
              switchPic,
              groupNames,
              delayTime: Number(data.delayTime?.data?.value || new Date().getTime()),
            })
          );
          ty.hideLoading();
        })
        .catch(err => {
          console.log('=== storage.get failed', err);
          ty.hideLoading();
        });
    }

    render() {
      const { extraInfo } = this.props;

      return (
        <Provider store={store}>
          <Panel>
            {/* @ts-ignore */}
            <SubComp extraInfo={extraInfo} {...this.props} />
          </Panel>
        </Provider>
      );
    }
  };
};

export default composeLayout;
